package com.msh.automatic.android.control.util

import android.content.Context
import android.content.SharedPreferences
import com.auth0.jwt.JWT
import com.auth0.jwt.interfaces.DecodedJWT
import java.util.Date

object ConfigUtil {

    private var token: String? = null
    private var jwt: DecodedJWT? = null

    fun get(context: Context,name:String,key:String):String?{
        val prefs = context.getSharedPreferences(name, Context.MODE_PRIVATE)
        return prefs.getString(key, null)
    }
    fun setString(context: Context,name:String,key:String,value:String){
        val prefs = context.getSharedPreferences(name, Context.MODE_PRIVATE)
        val editor = prefs.edit()
        editor.putString(key,value)
        editor.commit()
    }
    fun remove(context: Context,name:String,key:String){
        val prefs = context.getSharedPreferences(name, Context.MODE_PRIVATE)
        val editor = prefs.edit()
        editor.remove(key)
        editor.commit()
    }

    fun getToken():String?{
        return this.token
    }
    fun getToken(context: Context):String?{
        if(token != null){
            return token
        }
        this.token = get(context,"root","token")
        return this.token
    }

    fun setToken(context: Context,token:String){
        this.token = token
        this.jwt = getJwt(context)
        setString(context,"root","token",token)
    }
    fun removetToken(context: Context){
        this.token = null
        this.jwt = null
        remove(context,"root","token")
    }

    fun getJwt(context: Context): DecodedJWT? {
        if(jwt != null){
            return jwt
        }
        val token = getToken(context) ?: return null
        this.jwt = JWT.decode(token)
        return this.jwt
    }

    fun isActivation(context: Context): Boolean {
        val jwt = getJwt(context) ?: return false
        return jwt.expiresAt?.after(Date())!!
    }

}